package com.wbw.csnd_hd.service.Impl;

import com.wbw.csnd_hd.Utils.RedisUtils;
import com.wbw.csnd_hd.common.ConstantCommon;
import com.wbw.csnd_hd.common.ResultCommon;
import com.wbw.csnd_hd.common.ResultEnum;
import com.wbw.csnd_hd.mapper.AreaMapper;
import com.wbw.csnd_hd.pojo.Area;
import com.wbw.csnd_hd.service.AreaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class AreaServiceImpl implements AreaService {

    @Autowired
    AreaMapper areaMapper;

    @Autowired
    RedisUtils redisUtils;

    @Override
    public ResultCommon find() {
        //先去redis中查询所有库区的id集合
        Set<Object> all = redisUtils.sgetAll(ConstantCommon.AREA.AREA_ID_ALL);
        if (all==null){
            //说明redis中没有数据,去数据库中查询
            List<Area> areas = areaMapper.find();
            if (areas==null||areas.size()==0){
                //说明数据库中也没用数据
                return ResultCommon.fail(ResultEnum.FAIL_NO_FIND);
            }
            //数据库中查询到了数据，获取所有数据的id集合，存入redis中
            all = areas.stream().map(area -> area.getNo()).collect(Collectors.toSet());
            redisUtils.ssetCollection(ConstantCommon.AREA.AREA_ID_ALL,all);
            return ResultCommon.success(areas);
        }
        //redis中有数据
        List<Area> collect = all.stream().map(o -> findByNo(o.toString()))
                .filter(resultCommon -> resultCommon.isSuccess())
                .map(resultCommon -> resultCommon.getData())
                .collect(Collectors.toList());
        return ResultCommon.success(collect);
    }

    @Override
    public ResultCommon<Area> findByNo(String no) {
        //先去redis中查询
        String key = ConstantCommon.AREA.AREA_ID_PERFIX + no;
        Area hmget = redisUtils.hmget(key, Area.class);
        if (hmget == null) {
            //redis没查询到
            hmget = areaMapper.findByNo(no);
            if (hmget == null) {
                //数据库也没查询到
                return ResultCommon.fail(ResultEnum.FAIL_NO_FIND);
            }
            //数据库中查询到了数据，存入redis
            redisUtils.hmset(key,hmget);
        }
        //redis查询到了数据
        return ResultCommon.success(hmget);
    }
}
